package com.gh.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gh.reggie.common.R;
import com.gh.reggie.entity.Employee;
import com.gh.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;


@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     * @param request
     * @param employee
     * @return
     */
    //接收请求形式是post形式的，所以采用PostMapping来显示获取pos请求对应数据
    //请求中数据以json形式发送，传参中使用requestBody获得携带的json数据，并且将employee封装成对象
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){

        //1.将页面提交的页面用密码用Md5工具类加密
        String passward  = employee.getPassword();
        passward = DigestUtils.md5DigestAsHex(passward.getBytes());

        //查询用户的username在数据库中是否存在
        //由于username字段是唯一的，可以使用getOne方法查询唯一结果；
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);

        //跟据username查询，如果查询结果为空，直接返回不存在；
        if(emp == null){
            return R.error("用户不存在");
        }
        //有查询结果，比对密码，错误就返回；
        if(!emp.getPassword().equals(passward)){
            return R.error("密码错误123");
        }
        //校验用户状态，0为禁用，1为正常；
        if(emp.getStatus() == 0){
            return R.error("账号已禁用!");
        }

        //成功返回键值对
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);

    }

    /**
     * logout员工退出
     * @param request
     * @return
     */

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("employee");

        return R.success("退出成功");
    }

    /**
     * 新增员工
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> sava(HttpServletRequest request,@RequestBody Employee employee){
        log.info("新增员工，员工信息为：{}",employee.toString());


        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //获取存在Session中的id
        Long empId = (Long)request.getSession().getAttribute("employee");

        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);
        employeeService.save(employee);


        log.info("插入成功");
        return R.success("添加员工成功");
    }

    /**
     * 员工分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        log.info("page = {},pageSize = {},name = {}",page,pageSize,name);

        //构建分页构造器
        Page pageInfo  = new Page(page,pageSize);


        //构建条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        //执行查询
        //将分页参数page(此处时pageInfo)作为Mybatis或Mybatis Plus的第一个参数传入持久层函数，即可完成分页查询
        employeeService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 修改状态
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request,@RequestBody Employee employee){
        log.info("id为{}的员工状态为{}",employee.getId(),employee.getStatus());
        log.info("id为{}的员工状态为{}"+employee.toString());
        log.info(employee.toString());

        log.info("线程id为{}",Thread.currentThread().getId());
        Long empId= (Long)request.getSession().getAttribute("employee");
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(empId);

        employeeService.updateById(employee);
        return R.success("状态转换成功！");

    }


    /**
     * 根据员工id查询信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        log.info("根据员工id查员工信息。。。。");
        Employee employee = employeeService.getById(id);
        if(employee != null){
            return R.success(employee);
        }
        return R.error("查询员工信息失败！");
    }







}
